import { Trees } from '@/services/assets_category';
import { RequestOptionsType } from '@ant-design/pro-components';
import { GetProp, TreeSelect, TreeSelectProps } from 'antd';
import { useEffect, useState } from 'react';

/*
 * @Author: sonss
 * @Date: 2024-08-28 22:11:29
 * @LastEditTime: 2024-08-29 00:21:28
 * @FilePath: /ss-file-antd/src/components/Form/AssetsCategorySelect.tsx
 * @Description:  资源分类选择
 */
type AssetsCategorySelectProps = {
  value?: TreeSelectProps['value'];
  onChange?: (value: any) => void;
};

type DefaultOptionType = GetProp<TreeSelectProps, 'treeData'>[number];

const AssetsCategorySelect: React.FC<AssetsCategorySelectProps> = (props) => {
  const [treeData, setTreeData] = useState<Omit<DefaultOptionType, 'label'>[]>([]);

  const parse = (child: ASSETS.CATEGORY.Tree): RequestOptionsType => {
    const tree: RequestOptionsType = {
      title: child.name,
      value: child.id,
    };

    if (child.children && child.children.length > 0) {
      tree.children = child.children.map((v) => parse(v));
    }
    return tree;
  };

  useEffect(() => {
    Trees().then((res) => {
      if (res.code !== 0) {
        return;
      }
      const values = (res.data?.list || []).map((v) => parse(v));
      setTreeData(values);
    });
  }, []);

  const handleSelect = (value: any) => {
    if (props.onChange) {
      props.onChange(value);
    }
  };

  const handleClear = () => {
    if (props.onChange) {
      props.onChange(undefined);
    }
  };

  return (
    <TreeSelect
      placeholder="选择分类"
      treeData={treeData}
      value={props.value}
      allowClear={true}
      onSelect={handleSelect}
      onClear={handleClear}
    />
  );
};

export default AssetsCategorySelect;
